<?php

namespace App\Model\Dao;

use App\Concern\BaseDao;
use App\Utils\CustomUtils;
use Cassandra\Custom;
use Hyperf\Database\ConnectionInterface;
use App\Utils\RedisUtils;
use Hyperf\Database\Query\Builder;
use Hyperf\DbConnection\Db;
use Hyperf\Utils\Arr;

/**
 * SysAdminDao
 */
class SysAdminDao extends BaseDao {

    /**
     * 表名常量
     * 联表的时候通过XxxDao::TABLE获取
     */
    const TABLE = "sys_admin";

    // 不支持软删除
    protected $softDelete = null;

    /**
     * 父类中通过静态函数获取表名, 因为不能通过静态常量获取, 这个函数是固定写在子类中的
     */
    public static function table (): string {
        return self::TABLE;
    }

    protected function _buildConnectionTable() : ConnectionInterface{
        return Db::connection();
    }

    /**
     * @return array
     * 获取全部
     */
    public function getAllSales($level = []) {
        $main = sprintf("%s AS main", self::TABLE);
        $role = sprintf("%s AS role", SysRoleDao::table());
        $builder = $this->_buildConnectionTable()->table($main)
            ->leftJoin($role, "main.roleId", "=", "role.id")
            ->where("role.extraType", 1);
        !empty($level) && $builder = $builder->whereIn("main.level", $level);
        $builder = $builder->orderBy("main.createTime", 'desc');
        $data = $builder->selectRaw("main.id, main.username, main.level, main.parentId")->get()->toArray();
        return $data;
    }

    /**
     * @param $userIds
     * @param $level
     * @return array
     * 根据id
     */
    public function getSalesByIds($userIds = [], $level = []) {
        $main = sprintf("%s AS main", self::TABLE);
        $role = sprintf("%s AS role", SysRoleDao::table());
        $builder = $this->_buildConnectionTable()->table($main)
            ->leftJoin($role, "main.roleId", "=", "role.id")
            ->where("role.extraType", 1);
        !empty($level) && $builder = $builder->whereIn("main.level", $level);
        !empty($userIds) && $builder = $builder->whereIn("main.id", $userIds);

        $builder = $builder->orderBy("main.createTime", 'desc');
        $data = $builder->selectRaw("main.id, main.username, main.level, main.parentId")->get()->toArray();
        return $data;
    }

    public function getParentByChildrenIds($userIds = []) {
        $main = sprintf("%s AS main", self::TABLE);
        $role = sprintf("%s AS role", SysRoleDao::table());
        $builder = $this->_buildConnectionTable()->table($main)
            ->leftJoin($role, "main.roleId", "=", "role.id")
            ->where("role.extraType", 1);
        !empty($userIds) && $builder = $builder->whereIn("main.id", $userIds);
        $builder = $builder->where("main.level", 2)
            ->orderBy("main.createTime", 'desc');
        $data = $builder->selectRaw("distinct(main.parentId) as id, main.username, main.level")->get()->toArray();
        return $data;
    }

    /**
     * 排序
     *
     * @param Builder $builder
     * @param array   $params
     *
     * @return Builder|mixed
     */
    protected function _buildOrder (Builder $builder, $params = []) {

        // 通过前端提交的参数排序
        if (Arr::exists($params, "orderBy")) {

            [$prop, $order] = $params["orderBy"];

            if (in_array($order, ["asc", "desc"])) {

                //switch ($prop) {
                //    case "yieldMonth":
                //        $builder->orderBy("main.yieldMonth", $order);
                //        break;
                //    default:
                //        break;
                //}
            }
        }

        // 如果友其他固定的排序需求, 在这里写, 例如按照时间降序
        $builder->orderBy("createTime", "desc");

        // 追加父类的排序, 父类按照ID升序, 保证排序结果唯一
        return parent::_buildOrder($builder, $params);
    }

    /**
     * 查询条件
     *
     * @param $params
     *
     * @return Builder
     */
    protected function _buildQueryString ($params) {

        // 本表一律命名为main
        $main = sprintf("%s AS main", self::TABLE);

        // 联表表明获取
        //$country = sprintf("%s AS country", CountryDao::TABLE);

        $builder = DB::table($main);

        // 通过 Arr::exists 来判断是否存在该键, isset不准确
        Arr::exists($params, "username") && $builder->where("main.username", "like", "%{$params['username']}%");
        Arr::exists($params, "email") && $builder->where("main.email", $params['email']);
        Arr::exists($params, "roleId") && $builder->where("main.roleId", $params['roleId']);
        Arr::exists($params, "status") && $builder->where("main.status", $params['status']);
        Arr::exists($params, "createTimeRange")  && $builder->whereBetween('main.createTime',$params['createTimeRange']);
        return $builder;
    }

    public function setLoginInfo(string $userId, string $jwtToken)
    {
        $ttl = (int)config('jwt.ttl');
        // CustomUtils::xzxDebug($ttl);
        RedisUtils::redisResource()->set("admin_LOGINED::USERID_". $userId, $jwtToken, $ttl);                
        return;
    }
    
    public function getLoginInfo(string $userId)
    {
        return RedisUtils::redisResource()->get("admin_LOGINED::USERID_". $userId);
    }

    public function getOption($params) {
        $main = sprintf("%s AS main", self::TABLE);
        $role = sprintf("%s AS role", SysRoleDao::TABLE);
        $builder = DB::table($main)->leftJoin($role, "main.roleId", "=", "role.id");
        (Arr::exists($params, "extraType") && !empty($params['extraType'])) && $builder->where("role.extraType", "=", $params['extraType']);
        return $builder->selectRaw("main.id as value, main.username as label")
            ->orderByDesc("main.createTime")->get()->toArray();
    }
}
